﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class clientEdit : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CSUtils.CheckSession();
            this.binddataUserName();
            this.binddataPaymentName();
            this.binddataShippFreeName();
            this.binddataState();
            string clientID = Request.Params["clientID"];
            if (clientID != null && clientID != "")
            {
                this.showdata(clientID);
            }
            else
            {
                LabelClientCode.Text = "系统稍候生成";
                LabelClientName.Text = "新建客户";
                // set Defatult date
                DateTime tmpDate = DateTime.Now;
                TextBoxCreateDate.Text = tmpDate.ToString("yyyy-MM-dd");
            }
        }
        LabelErrorMsg.Text = "";
    }

    private void binddataUserName()
    {
        DropDownListUser.DataSource = CSUtils.getAllUserList("2");
        DropDownListUser.DataBind();
    }

    private void binddataPaymentName()
    {
        DropDownListPayment.DataSource = CSUtils.getAllPaymentTypeList();
        DropDownListPayment.DataBind();
    }

    private void binddataShippFreeName()
    {
        DropDownListShippingFree.DataSource = CSUtils.getAllShippingFreeTypeList();
        DropDownListShippingFree.DataBind();
    }


    private void binddataState()
    {
        DropDownListState.DataSource = CSUtils.getAllState();
        DropDownListState.DataBind();
    }


    private void showdata(string clientID)
    {
        LabelClientID.Text = clientID;
        ClientVO vo = CSUtils.getClient(clientID);
        LabelClientCode.Text = vo.ClientCode;
        TextBoxClientName.Text = vo.ClientName;
        DropDownListClientType.SelectedValue = vo.ClientType;
        DropDownListUser.SelectedValue = vo.UserID;
        DropDownListPayment.SelectedValue = vo.PaymentTypeID;
        DropDownListShippingFree.SelectedValue = vo.ShippingFreeTypeID;
        TextBoxPassword.Text = vo.ClientPassword;
        DropDownListArea.SelectedValue = vo.Area;
        DropDownListMarketType.SelectedValue = vo.MarketType;
        TextBoxState.Text = vo.State;
        TextBoxCity.Text = vo.City;
        TextBoxAddress.Text = vo.Address;
        TextBoxPostCode.Text = vo.PostCode;
        TextBoxPhone.Text = vo.Phone;
        TextBoxFax.Text = vo.Fax;
        TextBoxLinkman.Text = vo.Linkman;
        TextBoxCellphone.Text = vo.Cellphone;
        TextBoxEmail.Text = vo.Email;
        TextBoxCreditStatus.Text = vo.CreditStatus;
        TextBoxOther.Text = vo.Other;
        DropDownListClientStatus.SelectedValue = vo.ClientStatus;
        TextBoxContractBody.Text = vo.ContractBody;
        TextBoxContractMoney.Text = vo.ContractMoney;
        TextBoxBalanceInit.Text = vo.BalanceInit;
        TextBoxContractBrand.Text = vo.ContractBrand;
        TextBoxContractType.Text = vo.ContractType;
        TextBoxContractDateBegin.Text = vo.ContractDateBegin;
        TextBoxContractDateEnd.Text = vo.ContractDateEnd;
        TextBoxCreateDate.Text = vo.CreateDate;
        DropDownListBillCorp.SelectedValue = vo.BillCorp;
        TextBoxFreeDefine.Text = vo.FreeDefine;

        LabelClientName.Text = TextBoxClientName.Text;

        string state = TextBoxState.Text;
        ListItem liState = DropDownListState.Items.FindByText(state);
        if (liState != null)
        {
            liState.Selected = true;
            DropDownListCity.Items.Clear();
            DropDownListCity.Items.Add(new ListItem("请选择...", ""));
            DropDownListCity.DataSource = CSUtils.getAllCity(DropDownListState.SelectedValue);
            DropDownListCity.DataBind();
            string city = TextBoxCity.Text;
            ListItem liCity = DropDownListCity.Items.FindByText(city);
            if (liCity != null)
            {
                liCity.Selected = true;
            }
        }
    }


    private string save()
    {
        string clientID = LabelClientID.Text;
        ClientVO vo = null;
        if (clientID != "")
        {
            if (DropDownListClientStatus.SelectedValue != "正常")
            {
                //如果客户当前余额不为0, 客户状态不能变为“潜在，清理”
                double balance = CSUtils.getClientBalance(clientID);
                if (balance != 0)
                {
                    JScript.Alert("不能改变客户状态， 客户当前余额为:[" + balance + "], 请先结清！");
                    return "";
                }
            }

            //Update: get vo from db
            vo = CSUtils.getClient(clientID);
        }
        else
        {
            //New:
            if (this.haveReduplicate(TextBoxLinkman.Text.Trim()))
            {
                LabelErrorMsg.Text = "已有相同的联系人信息!";
                return "";
            }

            vo = new ClientVO();
            vo.ClientCode = this.getMaxClientCode();
        }
        vo.ClientName = TextBoxClientName.Text.Trim();
        vo.ClientType = DropDownListClientType.SelectedValue;
        if (DropDownListUser.SelectedValue != "")
        {
            vo.UserID = DropDownListUser.SelectedValue;
        }
        else
        {
            vo.UserID = "null";
        }
        vo.PaymentTypeID = DropDownListPayment.SelectedValue;
        vo.ShippingFreeTypeID = DropDownListShippingFree.SelectedValue;
        vo.ClientPassword = TextBoxPassword.Text;
        vo.Area = DropDownListArea.SelectedValue;
        vo.MarketType = DropDownListMarketType.SelectedValue;
        vo.State = TextBoxState.Text;
        vo.City = TextBoxCity.Text;
        vo.Address = TextBoxAddress.Text;
        vo.PostCode = TextBoxPostCode.Text;
        vo.Phone = TextBoxPhone.Text;
        vo.Fax = TextBoxFax.Text;
        vo.Linkman = TextBoxLinkman.Text;
        vo.Cellphone = TextBoxCellphone.Text;
        vo.Email = TextBoxEmail.Text;
        vo.CreditStatus = TextBoxCreditStatus.Text;
        vo.Other = TextBoxOther.Text;

        vo.ClientStatus = DropDownListClientStatus.SelectedValue;
        vo.ContractBody = TextBoxContractBody.Text;
        vo.ContractMoney = TextBoxContractMoney.Text;
        vo.BalanceInit = StringUtil.EmptyToZero(TextBoxBalanceInit.Text);

        vo.ContractBrand = TextBoxContractBrand.Text;
        vo.ContractType = TextBoxContractType.Text;
        if (TextBoxContractDateBegin.Text.Trim() == "")
        {
            vo.ContractDateBegin = "null";
        }
        else
        {
            vo.ContractDateBegin = "'" + TextBoxContractDateBegin.Text + "'";
        }

        if (TextBoxContractDateEnd.Text.Trim() == "")
        {
            vo.ContractDateEnd = "null";
        }
        else
        {
            vo.ContractDateEnd = "'" + TextBoxContractDateEnd.Text + "'";
        }

        vo.CreateDate = "'" + TextBoxCreateDate.Text + "'";
        vo.BillCorp = DropDownListBillCorp.SelectedValue;
        vo.FreeDefine = TextBoxFreeDefine.Text;

        try
        {
            if (CSUtils.mergeClient(vo))
            {
                return vo.ClientCode;
                
            }
            else
            {
                return "";                
            }
        }
        catch (Exception er)
        {
            LabelErrorMsg.Text = er.Message;
            return "";
            //throw;
        }

    }

    protected void ButtonSubmit_Click(object sender, EventArgs e)
    {
        string clientCode = this.save();
        if (clientCode != "")
        {
            Response.Redirect("clientManager.aspx?clientCode=" + clientCode);
        }
        else
        {
            JScript.Alert("保存失败！");
        }        
    }

    protected void ButtonSubmit2_Click(object sender, EventArgs e)
    {
        string clientCode = this.save();
        if (clientCode != "")
        {
            Response.Redirect("clientEdit.aspx");
        }
        else
        {
            JScript.Alert("保存失败！");
        }
    }

    protected void DropDownListState_SelectedIndexChanged(object sender, EventArgs e)
    {
        string stateID = DropDownListState.SelectedValue;
        DropDownListCity.Items.Clear();
        DropDownListCity.Items.Add(new ListItem("请选择...", ""));
        TextBoxCity.Text = "";
        if (stateID != "")
        {
            TextBoxState.Text = DropDownListState.SelectedItem.Text;            
            DropDownListCity.DataSource = CSUtils.getAllCity(stateID);
            DropDownListCity.DataBind();            
        }
        else
        {
            TextBoxState.Text = "";            

        }
    }

    protected void DropDownListCity_SelectedIndexChanged(object sender, EventArgs e)
    {
        string cityID = DropDownListCity.SelectedValue;
        if (cityID != "")
        {
            TextBoxCity.Text = DropDownListCity.SelectedItem.Text;
        }
        else
        {
            TextBoxCity.Text = "";
        }

    }

    private string getMaxClientCode()
    {
        string maxNumber = "";
        string sql =
            "select isnull(max(convert(int,client_code)),0)+1 as maxNumber from cs_client";

        DBConn myDB = new DBConn();
        SqlDataReader dr = myDB.getDataReader(sql);
        if (dr.Read())
        {
            maxNumber = dr["maxNumber"].ToString();
        }
        dr.Close();
        myDB.Close();

        if (maxNumber.Length == 1)
        {
            maxNumber = "0000" + maxNumber;
        }
        else if (maxNumber.Length == 2)
        {
            maxNumber = "000" + maxNumber;
        }
        else if (maxNumber.Length == 3)
        {
            maxNumber = "00" + maxNumber;
        }
        else if (maxNumber.Length == 4)
        {
            maxNumber = "0" + maxNumber;
        }
        else if (maxNumber.Length == 5)
        {
            ;
        }

        return maxNumber;        
    }

    private bool haveReduplicate(string linkman)
    {
        string n = "";
        string sql =
            "select count(client_id)as n from cs_client " +
            "where linkman = '" + linkman + "'";

        DBConn myDB = new DBConn();
        SqlDataReader dr = myDB.getDataReader(sql);
        if (dr.Read())
        {
            n = dr["n"].ToString();
        }
        dr.Close();
        myDB.Close();

        if (n == "0")
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    protected void ButtonDel_Click(object sender, EventArgs e)
    {
        string clientID = LabelClientID.Text;

        if (this.delClient(clientID))
        {
            JScript.Alert("删除成功！");
            Response.Redirect("clientManager.aspx");
        }
        else
        {
            JScript.Alert("删除失败！此客户在系统中发生过业务\\n请检查基础数据定义和业务单据！");
        }

    }


    private bool delClient(string clientID)
    {
        string sql =
            "delete from cs_client " +
            "where client_id = " + clientID;        
        
        DBConn myDB = new DBConn();
        int tmp;
        try
        {
            tmp = myDB.Update(sql);
        }
        catch
        {
            myDB.Close();
            return false;
        }
        myDB.Close();
        return (tmp > 0);

    }
    
}
